package com.thh.project.common.interceptor;

import com.thh.project.utils.common.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.MimeHeaders;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author thh
 * 拦截器  （项目请求数据存入日志）  可以在本类中写入自己定义的逻辑拦截
 */
@Component
public class CustomInterceptor implements HandlerInterceptor {
    /**
     * 记录日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //打印请求
        String method = request.getMethod();
        ////返回请求行中的资源名称
        String uri = request.getRequestURI();
        //获得客户端发送请求的完整url
        String url = request.getRequestURL().toString();
        //返回发出请求的IP地址
        String ip = request.getRemoteAddr();
        //返回请求行中的参数部分
        String params = request.getQueryString();
        LOGGER.info(String.format("%n请求url: %s%n请求方式: %s%nuri: %s%n请求ip: %s%n请求时间: %s%n请求参数: %s%n请求结果: %s", url, method, uri, ip, DateUtils.getCurrentDateTime(), params, "通过"));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.debug("postHandle method is now running!");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.debug("afterCompletion method is now running!");
    }
}
